package cz.pproproj.aaservice.aasbllmodule;

import cz.pproproj.aaservice.aasbllmodule.authentication.AuthenticationDataAccess;
import cz.pproproj.aaservice.aasbllmodule.authorization.AuthorizationModuleAccess;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.HashMap;
import java.util.Map;

/**
 * @author David
 * @since 18. 1. 2015
 */
public class BllModuleContext {
    private static final BllModuleContext INSTANCE = new BllModuleContext();
    private final Map<String, AuthenticationDataAccess> _authenticationDataAccessMap = new HashMap<>();
    private final AuthorizationModuleAccess _authorizationModuleAccess;

    public static BllModuleContext getInstance() {
        return INSTANCE;
    }

    private BllModuleContext() {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("authenticationDataSourcesConfig.xml");
        fillAuthenticationDataAccessMap(ctx);

        ctx = new ClassPathXmlApplicationContext("bllModuleContext.xml");
        _authorizationModuleAccess = ctx.getBean("authorizationModuleAccess", AuthorizationModuleAccess.class);
    }

    private void fillAuthenticationDataAccessMap(ApplicationContext ctx) {
        String[] usersDataAccessBeansNames = ctx.getBeanNamesForType(AuthenticationDataAccess.class);
        for (String uDABeanName : usersDataAccessBeansNames) {
            _authenticationDataAccessMap.put(uDABeanName, ctx.getBean(uDABeanName, AuthenticationDataAccess.class));
        }
    }

    public AuthenticationDataAccess getAuthenticationDataAccess(String dataSource) {
        return _authenticationDataAccessMap.get(dataSource);
    }

    public AuthorizationModuleAccess getAuthorizationDataAccess() {
        return _authorizationModuleAccess;
    }
}
